package com.qdlc.p2p.dal.dao.impl;

import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.exception.UserException;
import com.qdlc.p2p.dal.common.dao.jpa.BaseDaoImpl;
import com.qdlc.p2p.dal.dao.UserLoginDao;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserLogin;
import com.qdlc.p2p.dal.model.UserCacheModel;

@Repository("userLoginDao")
public class UserLoginDaoImpl extends BaseDaoImpl<UserLogin> implements UserLoginDao {

    private static Logger logger = Logger.getLogger(UserLoginDaoImpl.class);

    @Override
    public UserCacheModel getUserCache(long userId) {
        String sql = "SELECT u.real_name,u.mobile_phone,c.* " + "FROM " + Global.DB_PREFIX + "user u," + Global.DB_PREFIX + "user_cache c "
                + "WHERE u.user_id=c.user_id AND c.user_id = :userId";
        String[] names = new String[]{"userId"};
        Object[] values = new Object[]{userId};
        return findForUniqueBySql(sql, names, values, UserCacheModel.class);
    }

    @Override
    public void modifyPwd(User user) {
        String sql = "UPDATE UserLogin SET pwd = :pwd WHERE user.userId = :userId";
        //user.setPwd(MD5.encode(user.getPwd()));
        Query query = em.createQuery(sql);
        query.setParameter("pwd", user.getPwd());
        query.setParameter("userId", user.getUserId());
        int result = query.executeUpdate();
        logger.debug("用户修改密码, userId:" + user.getUserId() + " ,修改结果：" + result);
        if (result != 1) {
            throw new UserException("密码修改失败！");
        }
    }

    @Override
    public void modifyPaypwd(User user) {
        String sql = "UPDATE UserLogin SET payPwd = :payPwd WHERE user.userId = :userId";
        // user.setPayPwd(MD5.encode(user.getPayPwd()));
        Query query = em.createQuery(sql);
        query.setParameter("payPwd", user.getPayPwd());
        query.setParameter("userId", user.getUserId());
        int result = query.executeUpdate();
        if (result != 1) {
            throw new UserException("交易密码修改失败！");
        }
    }

    @Override
    public void updateStatus() {
        String sql = "UPDATE UserCache SET status = 0 WHERE status = 1";
        em.createQuery(sql).executeUpdate();
    }
}
